import "package:flutter/material.dart";
import "package:myapp/_common/NestedTabBarView.dart";
import "package:myapp/widget/keepAliveWrapper.dart";

import "widget/recommend/RecommendItemSwiperItem.dart"; //轮播图类型
import "widget/recommend/RecommendItemVideoItem.dart"; //视频类型
import "widget/recommend/RecommendItemAnimateItem.dart"; //番剧类型
import "widget/recommend/RecommendItemShopItem.dart"; //会员购类型
import "widget/recommend/RecommendItemImageTextItem.dart"; //图文类型
import "widget/recommend/RecommendItemLiveItem.dart"; //直播类型
import "widget/recommend/RecommendItemUPInfo.dart";

import "package:myapp/_common/UseRefresh.dart";

class RecommendItem {
  int occupy; //占行
  String type; //类型 swiper轮播图；video视频；animate番剧；shop会员购；imageText图文；live直播
  List<RecommendItemSwiperItem>? swiperList; //轮播图类型
  RecommendItemVideoItem? recommendItemVideoItem; //视频类型
  RecommendItemAnimateItem? recommendItemAnimateItem; //番剧类型
  RecommendItemShopItem? recommendItemShopItem; //会员购类型
  RecommendItemImageTextItem? recommendItemImageTextItem; //图文类型
  RecommendItemLiveItem? recommendItemLiveItem; //直播类型
  RecommendItemUPInfo? recommendItemUPInfo; //用户（或来源）信息
  RecommendItem({
    required this.type,
    required this.occupy,
    this.swiperList,
    this.recommendItemVideoItem,
    this.recommendItemAnimateItem,
    this.recommendItemShopItem,
    this.recommendItemImageTextItem,
    this.recommendItemLiveItem,
    this.recommendItemUPInfo,
  });
}

class RecommendView extends StatefulWidget {
  const RecommendView({super.key});
  @override
  State<StatefulWidget> createState() {
    return _RecommendViewState();
  }
}

class _RecommendViewState extends State<RecommendView> {
  bool thumbVisibility = false; //滚动条显示
  double recommendRowItemHeight = 280.0; //行占用高度
  double spacing = 5.0; //行顶部高度

  final double phoneMaxWidth = 420; //判断为手机的最大宽度
  final double padMaxWidth = 840; //判断为平板的最大宽度

  final List<RecommendItem> recommendList = [
    RecommendItem(
      occupy: 2,
      type: 'swiper',
      swiperList: [
        RecommendItemSwiperItem(
          title: '一曲东风破，忆起旧时光',
          imageUrl: "./images/1.jpg",
        ),
        RecommendItemSwiperItem(
          title: '照这样下去，她会疯的',
          imageUrl: "./images/2.jpg",
        ),
        RecommendItemSwiperItem(
          title: '预售开了快买票！一键直达猩世界',
          imageUrl: "./images/3.jpg",
        ),
      ],
    ),
    RecommendItem(
      occupy: 1,
      type: 'video',
      recommendItemVideoItem: RecommendItemVideoItem(
        coverUrl: "./images/1.jpg",
        playCount: "13.3万",
        danmuCount: "164",
        videoDuration: "1:22",
        title: '吃过我搭配的美食 每峰骆驼都会沦陷',
        likeCount: "1万",
        isVerticalScreen: true,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: 'animate',
      recommendItemAnimateItem: RecommendItemAnimateItem(
        playCount: '463.1万',
        likeCount: '30.3万',
        coverUrl: "./images/3.jpg",
        title: "先相信再相信！真是强而有力呀！",
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '夜晚的水母不会发光',
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: 'video',
      recommendItemVideoItem: RecommendItemVideoItem(
        coverUrl: "./images/1.jpg",
        playCount: "3.3万",
        danmuCount: "3913",
        videoDuration: "17:08",
        title: '《互联网热门帅哥赏析》：竟然你如此费心取悦，那我就不客气了！（第九期）',
        likeCount: "1万",
        isVerticalScreen: false,
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '正经的老邪',
        isSubscribed: true,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: 'video',
      recommendItemVideoItem: RecommendItemVideoItem(
        coverUrl: "./images/3.jpg",
        playCount: "7.3万",
        danmuCount: "57",
        videoDuration: "3:08",
        title: '女神椅，久坐人群的必需品！',
        likeCount: "2千",
        isHotLike: true,
        isVerticalScreen: false,
        isPromotion: true,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: "imageText",
      recommendItemImageTextItem: RecommendItemImageTextItem(
        coverUrl: "./images/3.jpg",
        likeCount: "1936",
        title: "看到这种图，我反手就是一个赞[脱单]\n茶乃xxx - 52644245",
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '星铁代肝-凌风',
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: "live",
      recommendItemLiveItem: RecommendItemLiveItem(
        coverUrl: "./images/1.jpg",
        viewCount: '1796',
        title: '闭麦修图',
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '外星嫣子',
        isSubscribed: true,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: "shop",
      recommendItemShopItem: RecommendItemShopItem(
        coverUrl: "./images/3.jpg",
        viewCount: "17.1万",
        hotCount: "503.9万",
        title: "原创 女仆姐姐 辛西娅 1/6手办",
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '猜你喜欢',
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: 'video',
      recommendItemVideoItem: RecommendItemVideoItem(
        coverUrl: "./images/1.jpg",
        playCount: "25.9万",
        danmuCount: "409",
        videoDuration: "2:58",
        title: "【梗百科】Omg It's XXX是啥梗？又萌又万用啊！？",
        likeCount: "1万",
        isHotLike: true,
        isVerticalScreen: false,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: 'video',
      recommendItemVideoItem: RecommendItemVideoItem(
        coverUrl: "./images/1.jpg",
        playCount: "25.9万",
        danmuCount: "409",
        videoDuration: "2:58",
        title: "【梗百科】Omg It's XXX是啥梗？又萌又万用啊！？",
        likeCount: "1万",
        isHotLike: true,
        isVerticalScreen: false,
      ),
    ),
    RecommendItem(
      occupy: 1,
      type: "live",
      recommendItemLiveItem: RecommendItemLiveItem(
        coverUrl: "./images/1.jpg",
        viewCount: '1796',
        title: '苦练三年，我要成为胡桃糕手',
        isPromotion: true,
        partition: '永劫无间',
      ),
      recommendItemUPInfo: RecommendItemUPInfo(
        name: '桃芙芙',
        isSubscribed: false,
        avatar: "./images/tab_1.jpg",
      ),
    ),
  ];

  // 列表触摸并开始滑动时，显示滚动条
  // 触摸结束等待500ms，隐藏滚动条(淡出)
  List<List<RecommendItem>> r = [];
  // [[2],[1,1],[1,1],[1,1],[2],[1,1],[1,1]]

  bool isRefreshing = false;

  @override
  void initState() {
    List<List<RecommendItem>> list = []; //整个待合并给recommend的数组
    List<RecommendItem> rowItem = []; //行包含的元素
    for (int i = 0; i < recommendList.length; i++) {
      var item = recommendList[i];
      if (item.occupy == 2) {
        if (rowItem.isEmpty) {
          list.add([item]);
        } else {
          // 如果_rowItem已存在内容，则先添加到list，在重新插入
          list.add(rowItem);
          rowItem = [item];
          list.add(rowItem);
          rowItem = [];
        }
      } else {
        if (rowItem.isEmpty) {
          rowItem.add(item);
        } else if (rowItem.length == 1) {
          rowItem.add(item);
          list.add(rowItem);
          rowItem = [];
        } else if (rowItem.length == 2) {
          list.add(rowItem);
          rowItem = [item];
          list.add(rowItem);
          rowItem = [];
        }
      }
    }
    r.addAll(list);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return UseRefresh(
      onRefresh: () async {
        setState(() {
          isRefreshing = true;
        });
        await Future.delayed(const Duration(seconds: 2));
        setState(() {
          isRefreshing = false;
        });
      },
      child: CustomScrollView(
        controller: NestedInnerScrollController.maybeOf(context),
        slivers: [
          // 处理嵌套遮挡问题
          SliverOverlapInjector(
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          ),
          SliverList.builder(
            itemCount: r.length,
            itemBuilder: (BuildContext context, int index) {
              List<RecommendItem> rowItemList = r[index]; //行

              return KeepAliveWrapper(
                child: CardWrapWidget(
                  spacing: spacing,
                  children: rowItemList.map((e) {
                    RecommendItemUPInfo? recommendItemUPInfo =
                        e.recommendItemUPInfo;
                    if (e.type == 'swiper') {
                      // 轮播图
                      var recommendItemSwiperList = e.swiperList ?? [];
                      return RecommendItemSwiperItemWidget(
                        recommendItemSwiperList: recommendItemSwiperList,
                      );
                    } else if (e.type == 'video') {
                      // 视频
                      var recommendItemVideoItem =
                          e.recommendItemVideoItem as RecommendItemVideoItem;
                      return RecommendItemVideoItemWidget(
                        recommendItemVideoItem: recommendItemVideoItem,
                        recommendItemUPInfo: recommendItemUPInfo,
                      );
                    } else if (e.type == 'animate') {
                      // 番剧
                      var recommendItemAnimateItem = e.recommendItemAnimateItem
                          as RecommendItemAnimateItem;
                      return RecommendItemAnimateItemWidget(
                        recommendItemAnimateItem: recommendItemAnimateItem,
                        recommendItemUPInfo: recommendItemUPInfo,
                      );
                    } else if (e.type == 'shop') {
                      // 会员购
                      var recommendItemShopItem =
                          e.recommendItemShopItem as RecommendItemShopItem;
                      return RecommendItemShopItemWidget(
                        recommendItemShopItem: recommendItemShopItem,
                        recommendItemUPInfo: recommendItemUPInfo,
                      );
                    } else if (e.type == 'imageText') {
                      // 图文
                      var recommendItemImageTextItem =
                          e.recommendItemImageTextItem
                              as RecommendItemImageTextItem;
                      return RecommendItemImageTextItemWidget(
                        recommendItemImageTextItem: recommendItemImageTextItem,
                        recommendItemUPInfo: recommendItemUPInfo,
                      );
                    } else if (e.type == 'live') {
                      // 直播
                      var recommendItemLiveItem =
                          e.recommendItemLiveItem as RecommendItemLiveItem;
                      return RecommendItemLiveItemWidget(
                        recommendItemLiveItem: recommendItemLiveItem,
                        recommendItemUPInfo: recommendItemUPInfo,
                      );
                    } else {
                      return const Text('其他类型');
                    }
                  }).toList(),
                ),
              );
            },
          )
        ],
      ),
    );
  }
}

// 卡片内容每一行容器
class CardWrapWidget extends StatelessWidget {
  final double spacing; //间隔
  final List<Widget> children;
  const CardWrapWidget({
    super.key,
    this.children = const [],
    required this.spacing,
  });
  @override
  Widget build(BuildContext context) {
    List<Card> rowChildren = [];
    for (int i = 0; i < children.length; i++) {
      if (i == 0) {
        rowChildren.add(Card(
          marginLeft: 0,
          marginRight: spacing / 2,
          child: children[i],
        ));
      } else if (i == children.length - 1) {
        rowChildren.add(Card(
          marginLeft: spacing / 2,
          marginRight: 0,
          child: children[i],
        ));
      } else {
        rowChildren.add(Card(
          marginLeft: spacing / 2,
          marginRight: spacing / 2,
          child: children[i],
        ));
      }
    }

    return Container(
      padding: EdgeInsets.only(top: spacing, left: spacing, right: spacing),
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children:
              rowChildren.map((e) => Expanded(flex: 1, child: e)).toList(),
        ),
      ),
    );
  }
}

class Card extends StatelessWidget {
  final Widget child;
  final double borderRadius;
  final double marginLeft;
  final double marginRight;
  const Card({
    super.key,
    required this.child,
    this.borderRadius = 4,
    this.marginLeft = 6,
    this.marginRight = 6,
  });
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: marginLeft, right: marginRight),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius),
        child: child,
      ),
    );
  }
}
